/*
 * Copyright 2020-2021 redragon.dongbin
 *
 * This file is part of redragon-erp/赤龙ERP.

 * redragon-erp/赤龙ERP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * redragon-erp/赤龙ERP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with redragon-erp/赤龙ERP.  If not, see <https://www.gnu.org/licenses/>.
 */
package com.erp.ledger.balance.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.redragon.framework.springmvc.ControllerSupport;
import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.redragon.framework.hibernate.data.RDDataBox;
import org.redragon.framework.hibernate.data.SnowFlake;
import org.redragon.framework.hibernate.model.Pages;
import org.redragon.framework.util.JsonDataUtil;
import org.redragon.framework.util.JsonUtil;
import org.redragon.framework.util.ShiroUtil;

import com.erp.dataset.service.DatasetCommonService;
import com.erp.ledger.account.dao.model.GLCodeCombinations;
import com.erp.ledger.account.dao.model.GLLedger;
import com.erp.ledger.account.service.GLCodeCombinationsService;
import com.erp.ledger.account.service.GLLedgerService;
import com.erp.ledger.balance.dao.model.GLBalance;
import com.erp.ledger.balance.dao.model.GLBalanceCO;
import com.erp.ledger.balance.service.GLBalanceService;
import com.erp.ledger.balance.util.GLBalanceUtil;
import com.erp.masterdata.calendar.dao.model.MdFinanceCalendarPeriod;
import com.erp.masterdata.calendar.dao.model.MdFinanceCalendarPeriodCO;
import com.erp.masterdata.calendar.service.MdFinanceCalendarPeriodService;
import com.erp.masterdata.common.service.MasterDataCommonService;
import com.erp.masterdata.eco.service.MasterDataEcoService;
import com.erp.masterdata.expense.dao.model.MdExpenseItem;
import com.erp.masterdata.subject.dao.model.MdFinanceSubject;
import com.erp.masterdata.subject.service.MdFinanceSubjectService;

@Controller
@RequestMapping("/web/gLBalance")
public class GLBalanceWebController extends ControllerSupport{
    
    //日志处理
    private Logger logger = LoggerFactory.getLogger(GLBalanceWebController.class);
    
    //服务层注入
    @Autowired
    private GLBalanceService gLBalanceService;
    @Autowired
    private DatasetCommonService datasetCommonService;
    @Autowired
    private MasterDataCommonService masterDataCommonService;
    @Autowired
    private GLCodeCombinationsService glCodeCombinationsService;
    @Autowired
    private MdFinanceCalendarPeriodService mdFinanceCalendarPeriodService;
    @Autowired
    private GLLedgerService glLedgerService;
    @Autowired
    private MdFinanceSubjectService mdFinanceSubjectService;
    
    @Override
    public String getExceptionRedirectUrl() {
        return this.getFormatRedirectUrl("getGLBalanceList");
    }
    
    
    
    /**
     * 
     * @description 查询数据列表
     * @date 2021-02-02 14:56:15
     * @author 
     * @param pages
     * @param gLBalanceCO
     * @param model
     * @return String
     *
     */
    @RequestMapping("getGLBalanceList")
    public String getGLBalanceList(Pages pages, GLBalanceCO gLBalanceCO, Model model) {
        //分页查询数据
        if(pages.getPage()==0) {
            pages.setPage(1);
        }
        
        //分类账
        GLLedger glLedger = this.glLedgerService.getPrimaryGLLedgerByLegal(ShiroUtil.getLegalCode());
        //期初状态
        String status = "N";
        
        //分页查询数据
        gLBalanceCO.setActualFlag("N");
        List<GLBalance> gLBalanceList = this.gLBalanceService.getDataObjects(pages, gLBalanceCO);
        //循环设置分类账名称
        for(GLBalance glBalance: gLBalanceList) {
            glBalance.setLedgerName(glLedger.getLedgerName());
            glBalance.setSubjectDesc(this.glCodeCombinationsService.getGLCodeCombinationsSegment(glBalance.getSubjectCode()));
            glBalance.setSubjectDescTitle(this.glCodeCombinationsService.getGLCodeCombinationsSegmentDesc(glBalance.getSubjectCode()));
            //判断期初状态
            if(glBalance.getStatus().contentEquals("Y")) {
                status = "Y";
            }
            //计算期末余额
            BigDecimal num1 = new BigDecimal(glBalance.getBeginDr()).subtract(new BigDecimal(glBalance.getBeginCr()));
            BigDecimal num2 = new BigDecimal(glBalance.getPeriodDr()).subtract(new BigDecimal(glBalance.getPeriodCr()));
            BigDecimal result = num1.add(num2);
            if(result.doubleValue()>0) {
                glBalance.setEndDr(result.doubleValue());
            }else if(result.doubleValue()<0){
                glBalance.setEndCr(-result.doubleValue());
            }
        }
        
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //期间
        Pages pages1 = new Pages();
        pages1.setPage(1);
        pages1.setMax(100);
        MdFinanceCalendarPeriodCO mdFinanceCalendarPeriodCO = new MdFinanceCalendarPeriodCO();
        mdFinanceCalendarPeriodCO.setCalendarCode(glLedger.getCalendarCode());
        //mdFinanceCalendarPeriodCO.setPeriodStatus("OPEN");
        List<MdFinanceCalendarPeriod> calendarPeriodList = this.mdFinanceCalendarPeriodService.getPeriodListByCalendarCode(pages1, mdFinanceCalendarPeriodCO);
        
        //获取是否可以设置期初
        int actualNum = 0;
        if(this.gLBalanceService.getGLBalanceNumForActual(glLedger.getLedgerCode())>0) {
            actualNum = 1;
        }
        //页面属性设置
        model.addAttribute("gLBalanceList", gLBalanceList);
        model.addAttribute("pages", pages);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("glLedger", glLedger);
        model.addAttribute("calendarPeriodList", calendarPeriodList);
        model.addAttribute("actualNum", actualNum);
        model.addAttribute("status", status);
        
        return "basic.jsp?content=gLBalance/gLBalanceList";
    }
    
    
    
    /**
     * 
     * @description 查询单条数据
     * @date 2021-02-02 14:56:15
     * @author 
     * @param gLBalance
     * @param model
     * @return String
     *
     */
    @RequestMapping("getGLBalance")
    public String getGLBalance(GLBalance gLBalance, Model model) {
        int actualNum = 0;
        //查询要编辑的数据
        if(gLBalance!=null&&gLBalance.getBalanceId()!=null) {
            gLBalance = this.gLBalanceService.getDataObject(gLBalance.getBalanceId());
            gLBalance.setSubjectDesc(this.glCodeCombinationsService.getGLCodeCombinationsSegment(gLBalance.getSubjectCode()));
            gLBalance.setSubjectDescTitle(this.glCodeCombinationsService.getGLCodeCombinationsSegmentDesc(gLBalance.getSubjectCode()));
            //获取是否可以设置期初
            if(this.gLBalanceService.getGLBalanceNumForActual(gLBalance.getLedgerCode())>0) {
                actualNum = 1;
            }
            //计算年初余额
            BigDecimal num1 = new BigDecimal(gLBalance.getBeginDr()).subtract(new BigDecimal(gLBalance.getBeginCr()));
            BigDecimal num2 = new BigDecimal(gLBalance.getPeriodDr()).subtract(new BigDecimal(gLBalance.getPeriodCr()));
            BigDecimal result = num1.add(num2);
            if(result.doubleValue()>0) {
                gLBalance.setEndDr(result.doubleValue());
            }else if(result.doubleValue()<0){
                gLBalance.setEndCr(-result.doubleValue());
            }
        }else {
            gLBalance.setBalanceCode(SnowFlake.getConcurrentId().toString());
        }
        
        //分类账
        GLLedger glLedger = this.glLedgerService.getPrimaryGLLedgerByLegal(ShiroUtil.getLegalCode());
        //币种
        Map currencyTypeMap = this.datasetCommonService.getCurrencyType();
        //期间
        Pages pages1 = new Pages();
        pages1.setPage(1);
        pages1.setMax(100);
        MdFinanceCalendarPeriodCO mdFinanceCalendarPeriodCO = new MdFinanceCalendarPeriodCO();
        mdFinanceCalendarPeriodCO.setCalendarCode(glLedger.getCalendarCode());
        //mdFinanceCalendarPeriodCO.setPeriodStatus("OPEN");
        List<MdFinanceCalendarPeriod> calendarPeriodList = this.mdFinanceCalendarPeriodService.getPeriodListByCalendarCode(pages1, mdFinanceCalendarPeriodCO);
        
        
        //页面属性设置
        model.addAttribute("gLBalance", gLBalance);
        model.addAttribute("currencyTypeMap", currencyTypeMap);
        model.addAttribute("glLedger", glLedger);
        model.addAttribute("calendarPeriodList", calendarPeriodList);
        model.addAttribute("actualNum", actualNum);
        
        return "basic.jsp?content=gLBalance/gLBalanceEdit";
    }
    
    
    
    /**
     * 
     * @description 编辑数据
     * @date 2021-02-02 14:56:15
     * @author 
     * @param gLBalance
     * @param bindingResult
     * @param model
     * @return String
     *
     */
    @RequestMapping("editGLBalance")
    public String editGLBalance(@Valid GLBalance gLBalance, BindingResult bindingResult, Model model, RedirectAttributes attr) {
        //参数校验
        Map<String, String> errorMap = this.validateParameters(bindingResult, model);
        if(errorMap.size()>0) {
            return "forward:getGLBalance";
        }
        
        //新增时验证科目不能重复
        if(gLBalance.getBalanceId()==null) {
            if(this.gLBalanceService.isExistBeginBalanceForSubject(gLBalance.getLedgerCode(), gLBalance.getSubjectCode())) {
                //提示信息
                model.addAttribute("hint", "hint");
                model.addAttribute("alertMessage", "当前科目结构已录入期初，不能重复录入");
                return "forward:getGLBalance";
            }
        }
        
        //获取分类账信息
        GLLedger glLedger = this.glLedgerService.getDataObject(gLBalance.getLedgerCode());
        
        try {
            //对当前编辑的对象初始化默认的字段
            //设置会计期间，如果账簿年初启用则为当期，如果年中启用则改为前一期
            if(glLedger.getStartupType().equals("YEAR_MIDDLE")) {
                //获取前一期
                MdFinanceCalendarPeriod period = this.mdFinanceCalendarPeriodService.getPreviousPeriod(gLBalance.getPeriodName());
                if(period!=null) {
                    gLBalance.setPeriodName(period.getPeriodName());
                }
            }
            
            gLBalance.setActualFlag("N");
            gLBalance.setJeHeadCode("0");
            gLBalance.setJeLineCode("0");
            if(gLBalance.getPeriodDr()==null) {
                gLBalance.setPeriodDr(0D);
            }
            if(gLBalance.getPeriodCr()==null) {
                gLBalance.setPeriodCr(0D);
            }
            if(gLBalance.getQuarterDr()==null) {
                gLBalance.setQuarterDr(0D);
            }
            if(gLBalance.getQuarterCr()==null) {
                gLBalance.setQuarterCr(0D);
            }
            if(gLBalance.getLedgerDr()==null) {
                gLBalance.setLedgerDr(0D);
            }
            if(gLBalance.getLedgerCr()==null) {
                gLBalance.setLedgerCr(0D);
            }
            if(gLBalance.getBeginDr()==null) {
                gLBalance.setBeginDr(0D);
            }
            if(gLBalance.getBeginCr()==null) {
                gLBalance.setBeginCr(0D);
            }
            if(gLBalance.getEndDr()==null) {
                gLBalance.setEndDr(0D);
            }
            if(gLBalance.getEndCr()==null) {
                gLBalance.setEndCr(0D);
            }
            //计算期间发生金额
            BigDecimal num1 = new BigDecimal(gLBalance.getBeginDr()).subtract(new BigDecimal(gLBalance.getBeginCr()));
            BigDecimal num2 = new BigDecimal(gLBalance.getEndDr()).subtract(new BigDecimal(gLBalance.getEndCr()));
            BigDecimal result = num2.subtract(num1);
            if(result.doubleValue()>0) {
                gLBalance.setPeriodDr(result.doubleValue());
            }else if(result.doubleValue()<0){
                gLBalance.setPeriodCr(-result.doubleValue());
            }
            
            //保存编辑的数据
            this.gLBalanceService.insertOrUpdateDataObject(gLBalance);
            //提示信息
            attr.addFlashAttribute("hint", "success");
        }catch(Exception e){
            e.printStackTrace();
            if(e.getCause()!=null&&e.getCause().getClass()==ConstraintViolationException.class) {
                //提示信息
                model.addAttribute("hint", "hint");
                model.addAttribute("alertMessage", "编码已存在，请重新输入");
                return "forward:getGLBalance";
            }else {
                throw e;
            }
        }
        
        return "redirect:getGLBalanceList";
    }
    
    
    
    /**
     * 
     * @description 删除数据
     * @date 2021-02-02 14:56:15
     * @author 
     * @param gLBalance
     * @return String
     *
     */
    @RequestMapping("deleteGLBalance")
    public String deleteGLBalance(GLBalance gLBalance, RedirectAttributes attr) {
        //删除数据前验证数据
        if(gLBalance!=null&&gLBalance.getBalanceId()!=null) {
            //删除数据
            this.gLBalanceService.deleteDataObject(gLBalance);
            //提示信息
            attr.addFlashAttribute("hint", "success");
        }
        
        return "redirect:getGLBalanceList";
    }
    
    
    
    /**
     * 
     * @description 判断科目是否存在期初（异步）
     * @date 2021年2月3日
     * @author dongbin
     * @param gLBalance
     * @return
     * @return String
     *
     */
    @RequestMapping("isExistBeginBalanceAjax")
    @ResponseBody
    public String isExistBeginBalanceAjax(GLBalance gLBalance) {
        if(StringUtils.isNotBlank(gLBalance.getLedgerCode())&&StringUtils.isNotBlank(gLBalance.getSubjectCode())) {
            if(this.gLBalanceService.isExistBeginBalanceForSubject(gLBalance.getLedgerCode(), gLBalance.getSubjectCode())) {
                return "Y";
            }
        }
        
        return "N";
    }
    
    
    
    /**
     * 
     * @description 判断科目是否存在期初（异步）
     * @date 2021年2月3日
     * @author dongbin
     * @param gLBalance
     * @return
     * @return String
     *
     */
    @RequestMapping("updateBeginBalanceStatus")
    public String updateBeginBalanceStatus(GLBalance gLBalance, RedirectAttributes attr) {
        if(StringUtils.isNotBlank(gLBalance.getLedgerCode())&&StringUtils.isNotBlank(gLBalance.getStatus())) {
            //生效则验证平衡表
            if(gLBalance.getStatus().contentEquals("Y")) {
                //获取期初的平衡表
                GLBalanceCO glBalanceCO = new GLBalanceCO();
                glBalanceCO.setStatus("N");
                glBalanceCO.setActualFlag("N");
                List<GLBalance> glBalanceList = this.gLBalanceService.getDataObjects(glBalanceCO);
                //验证平衡表
                String result = GLBalanceUtil.validateBalanceList(glBalanceList);
                
                if(result.equals("")) {
                    //更新状态
                    this.gLBalanceService.updateBeginBalanceStatus(gLBalance.getLedgerCode(), gLBalance.getStatus());
                    //提示信息
                    attr.addFlashAttribute("hint", "success");
                }else {
                    //提示信息
                    attr.addFlashAttribute("hint", "hint");
                    attr.addFlashAttribute("alertMessage", "<b>操作失败，期初试算不平衡：</b><br/>"+result.replace(",", "<br/>"));
                }
            }else {
                //更新状态
                this.gLBalanceService.updateBeginBalanceStatus(gLBalance.getLedgerCode(), gLBalance.getStatus());
                //提示信息
                attr.addFlashAttribute("hint", "success");
            }
            
        }
        
        return "redirect:getGLBalanceList";
    }
    
}
